<template>
  <div>
    <div id="container"></div>
  </div>
</template>

<script>
export default {
  props: ["list"],
  data() {
    return {
      locationList: [],
    };
  },
  mounted() {
    if (!window.AMap) {
      // 第一次加载
      window.onLoad = () => {
        // 如果高德js加载完毕了 那么 全局变量中肯定会一个  AMap 对象
        this.initCity(); //null
      };
      var url =
        "https://webapi.amap.com/maps?v=1.4.15&key=b3b1b097ceba43763bae6f6657fdb46b&callback=onLoad";
      var jsapi = document.createElement("script");
      jsapi.charset = "utf-8";
      jsapi.src = url;
      document.head.appendChild(jsapi);
    } else {
      this.initCity();
    }
  },
  watch: {
    list() {
      this.locationList = this.list;
    },
    locationList() {
      this.initCity(); //you
    },
  },
  methods: {
    initCity() {
      var that = this;
      var map = new AMap.Map("container");
        map.setZoom(10);
            try {
                map.setCenter(this.locationList[0].location);
            } catch (err) {}
      AMap.plugin("AMap.CitySearch", function () {
        var citySearch = new AMap.CitySearch();
        citySearch.getLocalCity(function (status, result) {
          if (status === "complete" && result.info === "OK") {
            // 查询成功，result即为当前所在城市信息
            if (!that.$route.query.cityName) {
              that.$router.push("/hotel?cityName=" + result.city);
              that.$message.success(result.city);
            }
          }
        });
      });
      // 添加一些分布不均的点到地图上,地图上添加三个点标记，作为参照
      this.locationList.forEach(function (marker) {
        new AMap.Marker({
          map,
          position: marker.location,
          title: marker.name,
          icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_bs.png",

        });
      });
    },
  },
};
</script>

<style lang="less" scoped>
#container {
  width: 420px;
  height: 260px;
}
</style>